package com.jianggujin.redis.dialog;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JToolBar;

import com.jianggujin.redis.MainFrame;
import com.jianggujin.redis.component.JEditorTable;
import com.jianggujin.redis.config.ConfigStore;
import com.jianggujin.redis.config.ConnectionConfig;
import com.jianggujin.redis.util.MessageUtils;
import com.jianggujin.redis.util.ResourceUtils;

public class ConnectionsDialog extends AbstractDialog {
    private JEditorTable connectionTable;
    private List<ConnectionConfig> configItems;
    private JButton addConnectionBtn;
    private JButton editConnectionBtn;
    private JButton cloneConnectionBtn;
    private JButton removeConnectionBtn;
    private JButton openConnectionBtn;
    private JButton cancelBtn;

    private ConnectionConfig selectConnectionConfig;

    private ConnectionsDialog(Frame parent) {
        super(parent);
    }

    private void initToolbar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        addConnectionBtn = new JButton(ResourceUtils.LOGO_ADD);
        addConnectionBtn.setToolTipText("Add connection");
        addConnectionBtn
                .addActionListener(e -> handleAddConnection(ConnectionSettingsDialog.connectionSetting(this, null)));
        toolBar.add(addConnectionBtn);

        editConnectionBtn = new JButton(ResourceUtils.LOGO_EDIT);
        editConnectionBtn.setToolTipText("Edit connection");
        editConnectionBtn.addActionListener(e -> handleEditConnection());
        toolBar.add(editConnectionBtn);

        cloneConnectionBtn = new JButton(ResourceUtils.LOGO_CLONE);
        cloneConnectionBtn.setToolTipText("Clone connection");
        cloneConnectionBtn.addActionListener(e -> handleCloneConnection());
        toolBar.add(cloneConnectionBtn);

        removeConnectionBtn = new JButton(ResourceUtils.LOGO_REMOVE);
        removeConnectionBtn.setToolTipText("Remove connection");
        removeConnectionBtn.addActionListener(e -> handleRemoveConnection());
        toolBar.add(removeConnectionBtn);
        this.add(toolBar, BorderLayout.NORTH);
    }

    private void initCenter() {
        configItems = ConfigStore.loadConfig();
        connectionTable = new JEditorTable(new String[] { "Name", "Address" }); // SwingUtils.newTable(connectionTableModel);
        if (configItems != null) {
            configItems.forEach(item -> {
                connectionTable.addRow(new Object[] { item.getName(), item.getAddress() });
            });
        }
        connectionTable.addTableMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
                    handleOpenConnection();
                }
            }
        });
        this.add(connectionTable);
    }

    private void initBottom() {
        Box bottom = Box.createHorizontalBox();
        bottom.add(Box.createHorizontalGlue());
        openConnectionBtn = new JButton("Open");
        openConnectionBtn.addActionListener(e -> handleOpenConnection());
        bottom.add(openConnectionBtn);

        cancelBtn = new JButton("Cancel");
        cancelBtn.addActionListener(e -> dispose());
        bottom.add(cancelBtn);
        this.add(bottom, BorderLayout.SOUTH);
    }

    @Override
    protected void initComponent() {
        initToolbar();
        initCenter();
        initBottom();
    }

    @Override
    protected void initDialog() {
        setTitle("Connections");
        setSize(400, 300);
        super.initDialog();
        this.setVisible(true);
    }

    /**
     * 添加连接配置
     * 
     * @param config
     */
    private void handleAddConnection(ConnectionConfig config) {
        if (config == null) {
            return;
        }
        // connectionTableModel.addRow(new Object[] { config.getName(),
        // config.getAddress() });
        connectionTable.addRow(new Object[] { config.getName(), config.getAddress() });
        configItems.add(config);
        ConfigStore.saveConfig(configItems);
    }

    /**
     * 编辑连接配置
     */
    private void handleEditConnection() {
        int index = connectionTable.getSelectedRow();
        if (index < 0 || index >= connectionTable.getRowCount()) {
            MessageUtils.showInfoMessage(this, "Please choose connection");
            return;
        }
        ConnectionConfig newConfig = ConnectionSettingsDialog.connectionSetting(this, configItems.get(index));
        if (newConfig == null) {
            return;
        }
        ConnectionConfig old = configItems.get(index);
        old.setName(newConfig.getName());
        old.setHost(newConfig.getHost());
        old.setPort(newConfig.getPort());
        old.setAuth(newConfig.getAuth());
        old.setKeysGlobStylePattern(newConfig.getKeysGlobStylePattern());
        old.setNamespaceSeparator(newConfig.getNamespaceSeparator());
        old.setConnectionTimeout(newConfig.getConnectionTimeout());
        old.setSoTimeout(newConfig.getSoTimeout());
        connectionTable.setValueAt(newConfig.getName(), index, 1);
        connectionTable.setValueAt(newConfig.getAddress(), index, 2);
        ConfigStore.saveConfig(configItems);
    }

    /**
     * 克隆连接配置
     */
    private void handleCloneConnection() {
        int index = connectionTable.getSelectedRow();
        if (index < 0 || index >= connectionTable.getRowCount()) {
            MessageUtils.showInfoMessage(this, "Please choose connection");
            return;
        }
        handleAddConnection(configItems.get(index));
    }

    /**
     * 移除连接配置
     */
    private void handleRemoveConnection() {
        int index = connectionTable.getSelectedRow();
        if (index < 0 || index >= connectionTable.getRowCount()) {
            MessageUtils.showInfoMessage(this, "Please choose connection");
            return;
        }
        configItems.remove(index);
        connectionTable.removeRow(index);
        ConfigStore.saveConfig(configItems);
    }

    /**
     * 打开指定连接
     */
    private void handleOpenConnection() {
        int index = connectionTable.getSelectedRow();
        if (index < 0 || index >= connectionTable.getRowCount()) {
            MessageUtils.showInfoMessage(this, "Please choose connection");
            return;
        }
        selectConnectionConfig = configItems.get(index);
        dispose();
    }

    /**
     * 连接
     * 
     * @param mainFrame
     * @return
     */
    public static ConnectionConfig connect(MainFrame mainFrame) {
        return new ConnectionsDialog(mainFrame).selectConnectionConfig;
    }
}
